#!/usr/bin/env python
# coding=utf-8
#
# 任务实体

import time
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.api import mail
from google.appengine.ext.webapp import util
import crondb
import logdb
import sys
import datetimetool
import emailtool
import re

class CronJobHandler(webapp.RequestHandler):
	def get(self):
		crons = crondb.listCronInfo()
		if crons:
			fdate = datetimetool.getCNnow()
			year = fdate.year
			month = fdate.month
			day = fdate.day
			hour = fdate.hour
			minute = fdate.minute
			second = fdate.second
			dayOfWeek = fdate.weekday()
			minute = int(minute / 5)
			#self.response.out.write('%d-%d-%d %d:%d:%d :%d:' % (year, month, day, hour, minute, second, dayOfWeek))
			for cron in crons:
				if cron.enabled:
					id = cron.key().id()
					title = cron.title
					url = cron.url
					cron_month = cron.month # 从1开始
					cron_dayOfMonth = cron.dayOfMonth # 从1开始
					cron_dayOfWeek = cron.dayOfWeek # 从0开始
					cron_hours = cron.hours # 从0开始
					cron_minutes = cron.minutes # 从0开始
					cron_sendSuccessMsg = cron.sendSuccessMsg
					cron_sendFailMsg = cron.sendFailMsg
					needRun = True
					if cron_month and cron_month[0] != -1:
						needRun = month in cron_month
					if needRun and cron_dayOfMonth and cron_dayOfMonth[0] != -1:
						needRun = day in cron_dayOfMonth
					if needRun and cron_dayOfWeek and cron_dayOfWeek[0] != -1:
						needRun = dayOfWeek in cron_dayOfWeek
					if needRun and cron_hours and cron_hours[0] != -1:
						needRun = hour in cron_hours
					if needRun and cron_minutes and cron_minutes[0] != -1:
						needRun = minute in cron_minutes
					if needRun:
						if url:
							bodyHead = " CronID: %d" % id
							bodyHead = "%s\r\n Title: %s" % (bodyHead, title)
							bodyHead = "%s\r\n Url: %s" % (bodyHead, url)
							try:
								result = urlfetch.fetch(url)
								bodyHead = bodyHead + "\r\n ResponseCode: %d\r\n" % result.status_code
								body = bodyHead
								if result.status_code == 200: # 执行成功
									content = result.content
									content = content[:500]
									#m = re.search(r'(?<=charset=).+(?=")', content)
									#if m:
									#	coding = m.group()
									#	try:
											#根据网页编码对网页进行解码
									#		content = content.decode(coding)
									#	except Exception, e:
									#		content = result.content
									#else:
									#	coding = '未知'
									#	content = result.content
									if cron_sendSuccessMsg:
										subject = str(fdate) + " Run Cron Job: " + title
										try:
											body = "%s \r\n\r\n %s" % (bodyHead, content.decode('utf8','replace'))
										except Exception, e:
											body = bodyHead
										emailtool.SendNoticeMail(subject, body)
									log = logdb.LogInfo ( cronID = id, content = body)
									logdb.addLogInfo(log)
								else: # 执行失败
									if cron_sendFailMsg:
										subject = str(fdate) + " Run Cron Job: " + title
										try:
											body = "%s \r\n\r\n %s" % (bodyHead, content.decode('utf8','replace'))
										except Exception, e:
											body = bodyHead
										emailtool.SendNoticeMail(subject, body)
									log = logdb.LogInfo ( cronID = id, content = body)
									logdb.addLogInfo(log)
							except Exception, e:
								log = logdb.LogInfo ( cronID = id, content = bodyHead + str(e))
								logdb.addLogInfo(log)

def main():
	#code = sys.getdefaultencoding()
	#if code != 'utf8':
	#	reload(sys)
	#	sys.setdefaultencoding('utf8')
	application = webapp.WSGIApplication([('/cron', CronJobHandler)],
		debug=True)
	util.run_wsgi_app(application)

if __name__ == '__main__':
	main()
